import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Arrays;

public class UDPServer {
    private DatagramSocket socket = null;
    //1.构造服务器
    public UDPServer(int serverPacket) throws SocketException {
        this.socket = new DatagramSocket(serverPacket);
    }
    //2.服务器启动
    private void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            //接受请求数据包
            DatagramPacket requestPacket = new DatagramPacket(new byte[2],2);
            socket.receive(requestPacket);
            //分析数据包,响应,这里省略,直接回显
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //制作响应数据包
            /*DatagramPacket responsePacket = new DatagramPacket(requestPacket.getData(),requestPacket.getData().length,
                                                               requestPacket.getSocketAddress());*/
            DatagramPacket responsePacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    requestPacket.getSocketAddress());
            //发送响应数据包
            socket.send(responsePacket);
            //日志记录请求和响应
            String response = new String(responsePacket.getData(),0,requestPacket.getLength());
            String log = String.format("%s,%s,%s",requestPacket.getSocketAddress(),
                                        request,response);
            System.out.println(log);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPServer udpServer = new UDPServer(9999);
        udpServer.start();
    }
}
